package com.ai.module.business.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.ai.module.chat.common.base.ThreadLocalContext;
import com.ai.module.chat.common.constant.ChatImagePointStringConstant;
import com.ai.module.chat.common.constant.RedisKeyStringConstant;
import com.ai.module.chat.common.constant.StringConstant;
import com.ai.module.chat.common.enu.ModelType;
import com.ai.module.business.service.MemberCenterService;
import com.ai.module.chat.config.advice.exception.BusinessException;
import com.ai.module.user.domain.entity.UserConfigEntity;
import com.ai.module.user.domain.entity.UserPointsRecordEntity;
import com.ai.module.user.domain.vo.UserLoginInfo;
import com.ai.module.user.domain.vo.UserTimeVo;
import com.ai.module.user.enu.PointSource;
import com.ai.module.user.service.ChatGptImageService;
import com.ai.module.user.mapper.UserConfigMapper;
import com.ai.module.user.service.UserConfigService;
import com.ai.module.user.service.UserPointsService;
import com.ai.module.chat.util.RedisTemplateUtils;
import com.ai.module.mj.constant.enums.TaskAction;
import com.ai.module.mj.constant.stringConstant.ReturnCode;
import com.ai.module.mj.domain.Task;
import com.ai.module.mj.domain.bo.UserPointsBo;
import com.ai.module.mj.service.ImageSubmitService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

/**
 * @author: MrHe
 * @create: 2024-01-22 23:30
 * @description: 用户操作 绘画 登录 等功能
 **/
@Slf4j
@Service
public class MemberCenterServiceImpl implements MemberCenterService {

    @Autowired
    @Lazy
    private ImageSubmitService submitService;

    @Autowired
    private ChatGptImageService chatImageService;

    @Autowired
    private UserConfigMapper userConfigMapper;

    @Autowired
    private UserPointsService userPointsService;
    

    @Override
    public void dealMidJourneyUserPoints(UserPointsBo userPointsBo,
                                         Task task) {
        String userOriginalToken = task.getLoginToken();
        String userTokenKey = String.format(RedisKeyStringConstant.USER_INFO, userOriginalToken);
        UserLoginInfo userLoginInfo = RedisTemplateUtils.get(userTokenKey);
        int costPoints = userPointsBo.getCost();
        // 积分规则为 10进制 , 快图50, 慢图20
        Integer beforePoints = userLoginInfo.getPoints();
        UserPointsRecordEntity userPoints = new UserPointsRecordEntity();
        BeanUtil.copyProperties(userPointsBo,userPoints);
        userPoints.setBeforePoints(beforePoints);
        userPoints.setUserId(userLoginInfo.getUuid());
        userPoints.setSourceId(task.getRobotId());
        userPoints.setSource(PointSource.commonImage);
        int lessPoint = userLoginInfo.getPoints() - costPoints;
        if (lessPoint <= 0){
            lessPoint = 0;
        }
//        userLoginInfo.setPoints(lessPoint);
        userLoginInfo.setRealPoints(lessPoint);
        task.setRealPoint(lessPoint);
        // 加锁  进行积分 修改
        ThreadLocalContext.initPoint(userOriginalToken,lessPoint);
//        if (lessPoint <= 0){
//            throw new BusinessException("用户积分不足,  画图失败", ReturnCode.POINT_LESS);
//        }
        userPoints.setAfterPoints(beforePoints - costPoints);
        //  修改用户积分逻辑
        UserConfigEntity userConfig = new UserConfigEntity();
        userConfig.setPoints(lessPoint);
        userConfigService.update(userConfig,
                new LambdaQueryWrapper<UserConfigEntity>()
                .eq(UserConfigEntity::getUserId, task.getUserId()));
        // todo 后期放进Redis 生成成功再处理
       userPointsService.save(userPoints);
    }




    @Override
    public  void checkUserPoints(UserLoginInfo userLoginInfo
            , int cost) {
        Integer points = userLoginInfo.getPoints();
        int pointsProtocol = userLoginInfo.getPointsProtocol();
        userLoginInfo.setRealPoints(userLoginInfo.getPoints() - cost);
        if ( pointsProtocol == 0 ){
            throw new BusinessException("积分兑换权限未开",ReturnCode.POINTS_AUTH);
        }
        if (points < cost){
            throw new BusinessException("积分不够",ReturnCode.POINT_LESS);
        }
        // ThreadLocalContext.initUserInfo(userLoginInfo);

    }

    @Override
    public void dealChatUserPoints(UserTimeVo userChatInfo) {
        long start = System.currentTimeMillis();
        String askContent = userChatInfo.getAskContent();
        String chatGptTalk = userChatInfo.getChatGptTalk();
        ModelType modelType = userChatInfo.getModelType();
        String loginToken = userChatInfo.getLoginToken();
        String userId = userChatInfo.getUser();
        Integer beforePoints = userChatInfo.getBeforePoints();

        if (StringUtils.isNotBlank(askContent)
            && StringUtils.isNotBlank(chatGptTalk)){
            int totalLength = askContent.length() + chatGptTalk.length();
            // 如果是VIP  且 是 chatGpt 3.0 则 免费
            Integer isVIP = userChatInfo.getIsVIP();
            if (isVIP == 1 &&  modelType==ModelType.CHAT_3){
                return;
            }
            int realCostI=0;
            int realPoint = 0;
            Double chat4Cost= 0.0;
            switch (modelType){
                case CHAT_3:
                    chat4Cost = ChatImagePointStringConstant.chat3Cost;
                    Double realCost = totalLength * chat4Cost;
                    realCostI = chat4Cost.intValue();

                    break;
                default:
                    chat4Cost = ChatImagePointStringConstant.chat4Cost;
//                    realCostI = ((Double)(totalLength * chat4Cost)).intValue();
                    realCostI = chat4Cost.intValue();
                    break;
            }
            UserPointsRecordEntity userPoints = new UserPointsRecordEntity();

            if (beforePoints>realCostI){
                if (realCostI == 0){
                    realCostI = 1;
                }
                realPoint = beforePoints-realCostI;
                userPoints.setAfterPoints(beforePoints-realCostI);
            }else {
                realPoint = 0;
                userPoints.setAfterPoints(0);
            }
            userPoints.setPointType(TaskAction.CHAT_AI);
            userPoints.setBusinessId(userChatInfo.getUuid());
            userPoints.setPrompt(askContent);
            userPoints.setModelType(modelType);
            userPoints.setUserId(userId);
            userPoints.setBeforePoints(beforePoints);
            userPoints.setSourceId(userChatInfo.getSourceId());
            userPoints.setSource(userChatInfo.getSource());
            userPointsService.save(userPoints);
            ThreadLocalContext.initPoint(loginToken, realPoint);
            // 修改用户配置数据
            UserConfigEntity userConfig = new UserConfigEntity();
            userConfig.setPoints(realPoint);
            userConfigService.update(userConfig,new LambdaQueryWrapper<UserConfigEntity>()
                    .eq(UserConfigEntity::getUserId, userId));
            log.info("开始用户对话积分处理,耗时[{}]",System.currentTimeMillis()-start);

        }



    }


    @Autowired
    private UserConfigService userConfigService;

    @Override
    public void checkChatPoint(ModelType modelType) {
        UserLoginInfo userLoginInfo = ThreadLocalContext.getUserLoginInfo();
        if (userLoginInfo ==null){
            log.error("用户数据缺失 userId [{}],userToken [{}]",ThreadLocalContext.getUserId(),ThreadLocalContext.get(StringConstant.TOKEN));
            throw new BusinessException("请重新登录",401);
        }
        Integer points = userLoginInfo.getPoints();
        switch (modelType) {
            case CHAT_3:
                if (userLoginInfo.getVip() == 1) {
                    return;
                }
                Double real3Point = points - ChatImagePointStringConstant.chat3Cost;
                        //userLength * StringConstant.chat3Cost;
                if (points <= 0 || real3Point.intValue() <= 0) {
                    throw new BusinessException("积分不够,请充值或者开通会员", ReturnCode.POINT_LESS);
                }
                userLoginInfo.setRealPoints(real3Point.intValue());
                break;
            default:
                Double realPoint = points -
//                        userLength *
                        ChatImagePointStringConstant.chat4Cost;
                if (points <= 0 || realPoint.intValue() <= 0) {
                    throw new BusinessException("积分不够,请充值", ReturnCode.POINT_LESS);
                }
                userLoginInfo.setRealPoints(realPoint.intValue());
                break;
        }
        // 判断是不是会员 判断模型

    }

}
